<template>
    <div class="goods-list">
        <div class="mui-card" v-for="(item,i) in cars" :key="item.c_p_id">
            <div class="mui-card-content">
                <div class="mui-card-content-inner">
                    <mt-switch v-model="item.c_selected" @change="updateSelected(item.c_p_id,item.c_selected)"></mt-switch>
                    <img :src="item.p_img" alt="">
                    <div class="info">
                        <h1>{{item.p_name}}</h1>
                        <div>
                            <span class="price">￥{{item.p_price}}  </span>
                            <div class="mui-numbox" data-numbox-min='1' data-numbox-max='9'>
                                <button class="mui-btn mui-btn-numbox-minus" type="button">-</button>
                                <input :id="'test'+i" class="mui-input-numbox" type="number" :value="item.c_num" readonly @change="updateNum(item.c_p_id,i)"/>
                                <button class="mui-btn mui-btn-numbox-plus" type="button">+</button>
				                    </div>
                            <a href="" @click.prevent="del(item.c_p_id,i)">删除</a>
                        </div>
                    </div>
                </div>
            </div>
            </div>

            <div class="mui-card">
                    <div class="mui-card-content">
                        <div class="mui-card-content-inner jiesuan">
                            <div class="left">
                                <p>总价（不包含运费）:</p>
                                <p>已勾选商品 <span class="red">{{this.$store.getters.getTotalPrice.num}}</span>   件，总价  ￥ <span class="red">{{this.$store.getters.getTotalPrice.val}}万</span></p>
                            </div>
                            <mt-button type="danger" @click="js()">去结算</mt-button>
                        </div>
                    </div>
            </div>
    </div>
</template>
<script>
import mui from '../../lib/mui/js/mui.min.js'
  export default {
    data(){
      return {
        cars:[],
      }
    },
    methods:{
      del(id,i){  
        this.cars.splice(i,1);
        this.$store.commit("delGoods",id);
        this.cars = JSON.parse(localStorage.getItem("cars"));
      },
      updateSelected(id,val){
        this.$store.commit("updateSelected",{id,val});
        this.cars = JSON.parse(localStorage.getItem("cars"));
      },
      updateNum(id,i){
        let val = document.getElementById('test'+i).value;
        this.$store.commit("updateNum",{id,val});
        this.cars = JSON.parse(localStorage.getItem("cars"));
      },
      // 添加
      addGs(info){
        // 注意selected 为 0 1
        info.c_selected=info.c_selected?1:0;
        info.c_status=info.c_status?1:0;
        this.$ajax({
          url:"before/addshopcar",
          method:"post",
          data:info
        }).then(resp=>{
          if(resp.data.status === 1){
            console.log("添加成功");
          }
        })
      },
      // 修改
      updGs(info){
        info.c_selected=info.c_selected?1:0;
        info.c_status=info.c_status?1:0;
        this.$ajax({
          url:"before/updateshopcar",
          method:"put",
          data:info
        }).then(resp=>{
          if(resp.data.status === 1){
            console.log("修改成功");
          }
        })
      },
      // 删除
      delGs(id){
        this.$ajax({
          url:"before/deleteshopcar/"+id,
          method:"delete"
        }).then(resp=>{
          if(resp.data.status === 1){
            console.log("删除成功");
          }
        })
      },
      // 结算
      js(){

        // 判断勾选状态
        let selectedNum = 0;
        this.cars.forEach(item=>{
          if(item.c_selected){
            selectedNum++;
          }
        })
        if(selectedNum===0){
          alert("您还未勾选商品,请选择您想购买的商品,亲");
          return;
        }

        let ids = this.$store.state.ids;
        let bdids = []; // 用来保存本地购物车的 ids
        this.cars.forEach(item=>{
          bdids.push(item.c_p_id);
        })
        // 看看本地是否包含数据库的goodsId
        ids.forEach(item=>{
          if(bdids.includes(item)){
            // 包含修改
            this.cars.some(c=>{
              if(c.c_p_id === item){
                this.updGs(c); // 必须传入商品对象
                return true;
              }
            })
          }else{
            // 不包含  删除
            this.delGs(item);
          }
        })
        
        bdids.forEach(item=>{
          if(!ids.includes(item)){
            this.cars.some(c=>{
              if(c.c_p_id === item){
                this.addGs(c);
                return true;
              }
            })
          }
        })
        this.cars.forEach(item=>{
          if(item.c_selected){
            this.$ajax({
              url:'before/deleteshopcar',
              method:'delete',
              query:{c_id:item.c_id,c_num:item.c_num}
            }).then(resp=>{
              
            })
          }
        })
        // 初始化购物车
        this.getCs();
        this.$router.push("/bill/carbill/"+this.$store.getters.getTotalPrice.val+'/'+bdids)   
        // window.location.reload();

      },
      getCs() {
        let ids = [];
        this.$ajax({
          url: "before/shopcar",
          method:"get"
        }).then(resp => {
          resp.data.message.forEach(item => {
            
            ids.push(item.c_p_id);
            if (item.c_selected == 1) {
              item.c_selected = true;
            } else {
              item.c_selected = false;
            }
            if (item.c_status == 1) {
              item.c_status = true;
            } else {
              item.c_status = false;
            }
          })
          // c_p_id,c_num,c_u_id,p_img,p_name,p_price,c_selected
          this.$store.commit("carsInit", resp.data.message);
          // 给ids赋值
          this.$store.commit("idsInit", ids);
          // 同时储存到本地
          localStorage.setItem("cars", JSON.stringify(this.$store.state.cars));
        })
      },
      initProp(){
        // let uid = localStorage.getItem("uid");
        let userInfobd = JSON.parse(localStorage.getItem("userInfo"));
        if(userInfobd.length==0){
          let userInfo = this.$store.getters.getUserInfo;
          if(userInfo.length==0){
            this.$router.push("/user/login");
            return;
          }
        }
      }
    },
    created(){
      // 先判断用户是否登录
      this.initProp();
      this.cars = JSON.parse(localStorage.getItem("cars"));
    },
    mounted(){
      mui('.mui-numbox').numbox();
    }
  }
</script>
<style scoped>
.mui-card-content-inner{
    display:flex;
    align-items: center;
}
img{
    width:60px;
    height: 60px;
}
h1{
    font-size:13px;

}
.price{
    color:red;
    font-weight: bold;
}
.jiesuan{
    display: flex;
    justify-content: space-around;
     
}
.red{
    color:red;
    font-weight: bold;
    font-size:20px;
}
</style>